<?php

namespace addons\mental\controller;

use addons\mental\model\WxUser as wxUserModel;
use addons\mental\library\Wechat;
use addons\mental\model\User;
use fast\Random;
use think\Config;
use think\Session;

class WxUser extends Base
{
    /**
     * 微信小程序创建用户，不登陆，只是保存登录态
     * @return array
     */
    private $types = ['wechat' => '\addons\mental\library\Wechat', 'qq' => '\addons\mental\library\Qq'];

    //公众号手动登录
    public function mpAuth()
    {
        $url = $this->request->param('url');
        $res = (new wxUserModel)->officialMiniLogin($url, 'snsapi_userinfo');
        $this->success('', $res['data']);
    }

    public function login1()
    {
        $code = $this->request->param('code');
        $type = $this->request->param('type', 'wechat'); //wechat / qq
        if (empty($code)) {
            $this->error('code', [], 1001);
        }
        //根据code取openid和session_key

        $model = new $this->types[$type];

        $result = $model->codeToSessionkey($code);

        if (!$result['status']) {
            $this->error($result['msg'], $result['data'], 1002);
        }

        $wxUserModel = new wxUserModel();
        $wx_user_id = $wxUserModel->codeToInfo($result, $type == 'wechat' ? 1 : 4); //1微信小程序，4QQ
        Session::set('wx_user_id', $wx_user_id);
        $this->success($result['msg']);
    }


    /**
     * Undocumented function
     * 微信小程序传过来了手机号码，那么取他的手机号码
     * @return void
     */
    public function login2()
    {
        $param = $this->request->param();
        $wx_user_id = Session::get('wx_user_id');
        if (empty($wx_user_id)) {
            $this->error('参数错误');
        }
        $type = $this->request->param('type');

        $wxUserModel = new wxUserModel();
        $info = $wxUserModel->where(['id' => $wx_user_id])->find();
        if (!$info) {
            $this->error(__('No results were found'));
        }

        $userInfo = null;

        if ($type == 'qq') {

            if (!isset($param['iv']) || empty($param['iv'])) {
                $this->error(sprintf(__("Parameter %s can not be empty"), 'iv'));
            }
            if (!isset($param['edata']) || empty($param['edata'])) {
                $this->error(sprintf(__("Parameter %s can not be empty"), 'edata'));
            }

            //解密数据信息
            $wechat = new Wechat();
            $result = $wechat->decrypt($param['edata'], $param['iv'], $info['session_key']);

            if (!$result['status']) {
                $this->error($result['msg']);
            }
            //判断数据的一致性
            if ($info['openid'] != $result['data']['openId']) {
                $this->error('数据不正确');
            }

            $userInfo = $result['data'];
        } else {

            if (!isset($param['userinfo']) || empty($param['userinfo'])) {
                $this->error(sprintf(__("Parameter %s can not be empty"), 'userinfo'));
            }

            $userInfo = $param['userinfo'];
        }


        if ($info->user_id != 0) {
            $this->auth->direct($info->user_id);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }

        //如果未开启手机号码绑定，直接创建账号登录
        if (Config::get('mental.is_bind_mobile') == 1) {
            $username = Random::alnum(20);
            $password = Random::alnum(6);
            $domain = request()->host();
            $ret = $this->auth->register($username, $password, $username . '@' . $domain, '', [
                'nickname' => $userInfo['nickName'],
                'avatar' => $userInfo['avatarUrl']
            ]);
            if (!$ret) {
                $this->error($this->auth->getError());
            }
            $info->user_id = $this->auth->id;
            $wxUserModel->updateWxInfo($info, $userInfo);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }

        $wxUserModel->updateWxInfo($info, $userInfo);
        Session::set('wx_user_id', $info['id']);
        $this->success('请绑定手机号码', 100);
    }
    /**
     * Undocumented function
     * 微信授权手机号码登录
     * @return void
     */
    public function getWechatMobile()
    {
        $encryptedData = $this->request->param('encryptedData');
        $iv = $this->request->param('iv');
        $wx_user_id = Session::get('wx_user_id');
        if (!$encryptedData) {
            $this->error(sprintf(__("Parameter %s can not be empty"), 'encryptedData'));
        }
        if (!$iv) {
            $this->error(sprintf(__("Parameter %s can not be empty"), 'iv'));
        }
        if (!$wx_user_id) {
            $this->error(sprintf(__("Parameter %s can not be empty"), 'wx_user_id'));
        }
        $wxUserModel = new wxUserModel();
        $info = $wxUserModel->where(['id' => $wx_user_id])->find();
        if (!$info) {
            $this->error(__('No results were found'));
        }
        //解密数据信息
        $wechat = new Wechat();
        $result = $wechat->decrypt($encryptedData, $iv, $info['session_key']);
        if (!$result['status']) {
            $this->error($result['msg'], $result['data']);
        }
        $mobile = $result['data']['phoneNumber'];
        $user = User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            //绑定到wxUser
            $info->user_id = $this->auth->id;
            $info->save();
            $userInfo = $this->auth->getUserinfo();
            $userInfo['avatar'] = cdnurl($userInfo['avatar'], true);
            $data = ['userinfo' => $userInfo];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
        $this->success('', $result);
    }
}
